// pages/activityState/activityState.js
const app = getApp();
const CryptoJS = require('../../utils/aes-jia.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index:null,
    payment: 0,
    stateArr:[
      {
        id:0,
        num:0,
        state:"待审核"
      },{
        id: 1,
        num: 0,
        state: "已通过"
      }, {
        id: 2,
        num: 0,
        state: "未通过"
      }
    ],
    activityState:[{}],
    actId:"",
    actType:"",
    type:"",
    infoType:1,
    openShow: false,//开红包
    gobackShow:false,//回礼
    isReq1: true,
    isReq2:false,
    ismodal:false,//弹窗
    thisData:"",//当前需要审核的所有信息
    thisName:"",
    createUid:"",
    returnId:"",
    sendUrl:"",
    sendName: "",
    sendId:"",
    sendMoney:"",
    returnMoney:"",
    returnThank:"",
    returnBlurMoney:"",
    showPopup:"",
    whetherSetPayPwd:"",//获取支付密码
    showPayPwdInput: false,
    payFocus: false,
    pwdVal:"",
    isOver: true,
    userInfo:"",
  },
  payment(e) {
    var id = e.currentTarget.dataset.index
    this.setData({
      payment: id
    })
  },
  getList(actid){
    var that = this;
    var uid = wx.getStorageSync('uid');
    app.req({
      url: that.data.type == "activity" ? "blessmini/enrol/checkList?uid=" + uid : "blessmini/enrol/getRegistrationInformation?uid=" + uid,
      data: {
        pageSize:10,
        pageNumber:1,
        // actId: "68cf6b3df96111e9945200163e05ff66"
        actId:actid,
        type: that.data.type == "activity" ? "" :that.data.infoType
      },
      success(res){
        console.log("报名列表",res)
        if(res.code == 200){
          // var item = that.data.activityState;
          // item.push(res.data.page.rows[0]);
          if (that.data.type == "activity"){
            that.setData({
              ['stateArr[0].num']: res.data.noCheck,
              ['stateArr[1].num']: res.data.checkNum,
              ['stateArr[2].num']: res.data.refuse,
              activityState: res.data.page.rows,
            })
          }else{
            that.setData({
              ['stateArr[0].num']: res.data.enrolmentNumber,
              ['stateArr[1].num']: res.data.seeNumber,
              ['stateArr[2].num']: res.data.signInNumber,
              activityState: res.data.blessEnrolList.rows,
            })
          }
        }
      },
      fail(err){
        console.log(err)
      }
    })
  },
  //切换查看
  cutCheck(e){
    if (e.currentTarget.dataset.item == "已报名"){
      this.setData({
        infoType:1,
        isReq2: false
      })
      if (!this.data.isReq1){
        wx.nextTick(() => {
          this.getList(this.data.actId);
          this.setData({
            isReq1: true
          });
        })
      }
    } else if (e.currentTarget.dataset.item == "已查看"){
      this.setData({
        infoType: 2,
        isReq1:false
      })
      if (!this.data.isReq2){
        wx.nextTick(() => {
          this.getList(this.data.actId);
          this.setData({
            isReq2: true
          });
        })
      }
    }
  },
  applyPass(e){
    var that = this;
    var info = e.currentTarget.dataset.item;
    if (info.checkStatus == 1){
      this.setData({
        thisName: info.name,
        ismodal:true,
        thisData:info
      })
    }
  },
  //处理审核
  deal(e){
    // console.log(e, this.data.thisData)
    if(e.currentTarget.dataset.type == "1"){
      this.doPass("1", this.data.thisData.id, this.data.thisData.userId)
    }else{
      this.doPass("2", this.data.thisData.id, this.data.thisData.userId)
    }
    this.setData({
      ismodal:false
    })
  },
  hide(){
    this.setData({
      ismodal:false
    })
  },
  //审核参与人
  doPass(type, id, userId){
    var that = this;
    var uid = wx.getStorageSync(uid)
    app.req({
      url:"blessmini/enrol/checkUser",
      method:"POST",
      data:{
        uid:uid,
        type:type,
        id:id,
        userId: userId,
        actId: that.data.actId,
        actType: that.data.actType,
      },
      success: function (res) {
        if (res.code == 200) {
          that.getList(that.data.actId);
        }
      },
    })
  },
  //显示礼金数
  openRedBox(e){
    this.setData({
      openShow:true,
      index:e.currentTarget.dataset.index
    })
    // console.log(e.currentTarget.dataset.item)
    var info = e.currentTarget.dataset.item
    this.setData({
      sendUrl: info.userUrl,
      sendName: info.name,
      sendMoney: info.money,
      sendId: info.userId,
      returnId: info.cashGiftId
    })
  },
  xCloseOpen(){
    this.setData({
      openShow: false,
    })
  },
  //打开回礼页
  jumpRedReturn() {
    this.setData({
      gobackShow: true,
      openShow:false
    })
  },
  xCloseReturn() {
    this.setData({
      gobackShow: false,
    })
  },
  // 关闭支付
  onClose() {
    this.setData({
      showPopup: false,
    })
  },
  preventTouchMove(){},
  //礼金额处理
  amountInput(e){
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    // console.log('bug1')
    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      // console.log('bug2')
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      // console.log('bug3')
      e.detail.value = 500000
    }
    this.setData({
      returnMoney: e.detail.value,
    })
  },
  returnInputBlur(e){
    if (e.detail.value !== '') {
      this.setData({
        returnBlurMoney: '￥' + this.data.returnMoney
      })
    }
  },
  returnfocus(e) {
    this.setData({
      returnBlurMoney: ''
    })
  },
  //礼金备注
  thankInput(e){
    this.setData({
      returnThank: e.detail.value
    })
  },
  // 打开支付选择
  returnMoneyBtn(){
    var that = this;
    if (that.data.returnMoney == 0 || that.data.returnMoney.length == 0) {
      wx.showToast({
        title: "回礼金额不能为空",
        icon: 'none',
        duration: 2000
      })
      return
    } else {
      that.setData({
        showPopup: true,
        gobackShow: false
      })
    }
  },
  //判断用户是否设置支付密码
  checkPayPassword(){
    var that = this;
    var uid = wx.getStorageSync('uid');
    if (uid == undefined || uid == '') {
      app.getUserInfo();
      return
    }
    app.req({
      url:"blessmini/user/whetherSetPayPwd",
      method:"post",
      data:{
        uid:uid
      },
      success(res){
        if(res.code == 200){
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      },
    })
  },
  //支付
  addToActivity1(e) {
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      var uid = wx.getStorageSync(uid);
      var walletBalance = "";
      app.req({
        url:"blessmini/user/myBalance",
        method:"post",
        data:{
          uid:uid
        },
        success(res){
          console.log(res)
          if(res.code == 200){
            walletBalance = res.data.balance;
            if (walletBalance < that.data.returnMoney) {
              // console.log("钱包余额", walletBalance, that.data.returnMoney)
              wx.showToast({
                title: "钱包余额不足",
                icon: 'none',
                duration: 2000
              })
              return
            } else {
              if (that.data.whetherSetPayPwd) {
                that.setData({
                  showPayPwdInput: true,
                  payFocus: true
                })
              } else {
                wx.showModal({
                  title: '温馨提示',
                  content: '为了您的账号安全，请设置支付密码',
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                      wx.navigateTo({
                        url: '/pages/password/password',
                      })
                    }
                  }
                })
              }
            }
          }
        },
        fail(){
          wx.showToast({
            title: "请确保网络通畅",
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  addToActivity: function (e) {
    var timestamp = Date.parse(new Date()) / 1000;
    var that = this;
    var payWay = '';
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.returnMoney)
    var blessings = (that.data.returnThank == '' ? '万分感谢，小小心意，请笑纳' : that.data.returnThank)
    if (e == 0) {
      payWay = 0
    } else {
      payWay = e.currentTarget.dataset.id;
    }
    if (payWay == 1) {
      var sourceType = 5
    } else {
      var sourceType = ''
    }
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      var userId = that.data.userInfo.id
      // console.log("支付方式", payWay, app.url)
      var data = {
        uid:wx.getStorageSync('uid'),
        birthId: that.data.actId,
        sendId: userId,
        type: 2,
        receiveId: that.data.sendId,
        content: blessings,
        money: that.data.returnMoney,
        payWay: parseInt(payWay),
        id: that.data.returnId,
        sourceType: sourceType,
        prepaymentRecordId: that.data.prepaymentRecordId,
      }
      console.log('传值', data)
      app.req({
        // url: 'blessmini/redPacket/returnSalute',
        url: 'blessmini/cashGift/returnCeremonyCashGift',
        method: "post",
        showLoad: true,
        data: data,
        success: function (res) {
          console.log("支付1", payWay,  that.data.returnMoney, res)
          if (res.code == 200 && payWay == 0) {
            that.data.activityState[that.data.index].isOpen=4
            that.setData({
              showPopup: false,
              isOver: true,
              activityState: that.data.activityState
            })
            wx.showToast({
              title: "红包已回赠",
              duration: 2000
            })
            // setTimeout(function(){
            //   that.getList(that.data.actId);
            // },2000)
          } else if (res.code == 200 && payWay == 1) {
            console.log("支付方式2", payWay)
            var paydata = res.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.data.activityState[that.data.index].isOpen = 4
                that.setData({
                  outTradeNo: paydata.outTradeNo,
                  showPopup: false,
                  isOver: true,
                   activityState: that.data.activityState
                })
                wx.showToast({
                  title: "红包已回赠",
                  duration: 2000
                })
                // setTimeout(function () {
                //   that.getList(that.data.actId);
                // }, 2000)
              },
              fail(res) {
                that.setData({
                  isOver: true
                })
                console.log("支付已取消")
                console.log(res.data.errMsg)
              }
            })
          } else {
            console.log("第三种方式")
            that.setData({
              isOver: true
            })
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },
  //获取焦点
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  //关闭支付框
  hidePayLayer: function () {
    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })
  },
  //输入密码监听
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    }
  },
  //预支付
  operationRecord() {
    var timestamp = Date.parse(new Date()) / 1000;
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.returnMoney)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "blessmini/webPayLog/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: ''
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: ''
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("上一页信息",options)
    this.setData({
      actId:options.actId,
      actType: options.actType,
      type: options.type,
      createUid: options.createUid
    })
    if (options.type == "activity"){
      wx.setNavigationBarTitle({
        title: '活动审核'
      })
    }else{
      wx.setNavigationBarTitle({
        title: '报名信息'
      })
      this.setData({
        ['stateArr[0].state']: "已报名",
        ['stateArr[1].state']: "已查看",
        ['stateArr[2].state']: "已签到",
      })
    }
    this.getList(options.actId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //判断用户是否设置支付密码
    this.checkPayPassword();
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo,
      })
    })
    // if (this.data.actId){
    //   this.getList(this.data.actId);
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})